import { Vector2 } from "../vector";  
import { Engine } from "../engine";  
import { CameraEffect } from "./camera-effect";  
import { lerp } from "../utils";  
  
export interface CinematicKeyframe {  
  time: number; // 0-1  
  cameraPos: Vector2;  
  focusOnPlayer: boolean;  
  playerOffset: Vector2;  
  zoom: number;  
}  
  
export class CinematicSceneEffect extends CameraEffect {  
  private keyframes: CinematicKeyframe[];  
  private currentKeyframe: number = 0;  
  
  constructor(engine: Engine, keyframes: CinematicKeyframe[]) {  
    super(engine);  
    this.keyframes = keyframes.sort((a, b) => a.time - b.time);  
  }  
  
  apply(basePos: Vector2): Vector2 {  
    if (!this.isActive || this.keyframes.length === 0) return basePos;  
  
    // 找到当前时间对应的关键帧  
    let currentFrame = this.keyframes[0];  
    let nextFrame = this.keyframes[1] || currentFrame;  
  
    for (let i = 0; i < this.keyframes.length - 1; i++) {  
      if (this.progress >= this.keyframes[i].time && this.progress <= this.keyframes[i + 1].time) {  
        currentFrame = this.keyframes[i];  
        nextFrame = this.keyframes[i + 1];  
        break;  
      }  
    }  
  
    // 计算关键帧间的插值进度  
    const frameProgress = nextFrame.time === currentFrame.time ? 0 :  
      (this.progress - currentFrame.time) / (nextFrame.time - currentFrame.time);  
  
    // 插值计算相机位置  
    let targetPos: Vector2;  
  
    if (currentFrame.focusOnPlayer || nextFrame.focusOnPlayer) {  
      // 聚焦角色模式  
      const playerPos = this.engine.player.body_.pos;  
      const canvas = this.engine.canvas_;  
        
      const currentOffset = currentFrame.focusOnPlayer ? currentFrame.playerOffset : new Vector2();  
      const nextOffset = nextFrame.focusOnPlayer ? nextFrame.playerOffset : new Vector2();  
        
      const interpolatedOffset = new Vector2(  
        lerp(currentOffset.x, nextOffset.x, frameProgress),  
        lerp(currentOffset.y, nextOffset.y, frameProgress)  
      );  
  
      targetPos = new Vector2(  
        playerPos.x - canvas.width / 2 + interpolatedOffset.x,  
        playerPos.y - canvas.height / 2 + interpolatedOffset.y  
      );  
    } else {  
      // 固定位置模式  
      targetPos = new Vector2(  
        lerp(currentFrame.cameraPos.x, nextFrame.cameraPos.x, frameProgress),  
        lerp(currentFrame.cameraPos.y, nextFrame.cameraPos.y, frameProgress)  
      );  
    }  
  
    // 应用缩放  
    const zoom = lerp(currentFrame.zoom, nextFrame.zoom, frameProgress);  
    if (zoom !== 1) {  
      const canvas = this.engine.canvas_;  
      const centerX = canvas.width / 2;  
      const centerY = canvas.height / 2;  
        
      targetPos.x = (targetPos.x - centerX) * (2 - zoom) + centerX;  
      targetPos.y = (targetPos.y - centerY) * (2 - zoom) + centerY;  
    }  
  
    return targetPos;  
  }  
}